# main.py
import os
import threading
import time
from config import (KNOWLEDGE_FILES, TOTAL_QUESTIONS, TOTAL_SCORE, CACHE_DIR)
from vector_processor import KnowledgeBaseProcessor
from knowledge_graph import KnowledgeGraphProcessor
from question_generator import QuestionGenerator
from grader import ScoringModule
from utils import get_multiline_input, check_abnormal_answer


def main():
    print("===== 大数据基础知识章节测试系统启动 =====")

    print("\n--- 可测试章节 ---")
    chapter_map = {i + 1: file_path for i, file_path in enumerate(KNOWLEDGE_FILES)}
    for num, path in chapter_map.items():
        chapter_name = os.path.basename(path).replace(".txt", "").replace(".docx", "")
        print(f"  - 第{num}章: {chapter_name}")

    while True:
        try:
            chapter_choice = int(input("\n请选择要测试的章节号（例如: 1）："))
            if chapter_choice not in chapter_map:
                print("无效的章节号，请重新输入。")
                continue
            break
        except ValueError:
            print("输入无效，请输入一个数字。")

    selected_file = chapter_map[chapter_choice]

    vector_store_path = os.path.join(CACHE_DIR, f"vector_store_ch{chapter_choice}")
    kg_cache_path = os.path.join(CACHE_DIR, f"kg_cache_ch{chapter_choice}.json")

    # 3. 初始化模块
    kg_ready_event = threading.Event()
    kb_processor = KnowledgeBaseProcessor(knowledge_files=[selected_file], vector_store_path=vector_store_path)
    kg_processor = KnowledgeGraphProcessor(kg_cache_path=kg_cache_path)
    question_generator = QuestionGenerator(kb_processor, kg_processor, kg_ready_event)
    scoring_module = ScoringModule(kb_processor, kg_processor)

    # 4. 数据准备：加载文档、构建向量存储和知识图谱
    print("\n--- 知识库准备中 ---")
    start_time = time.time()
    try:
        # 加载选定章节的文档
        kb_processor.load_documents()

        # 获取当前文件的元数据
        current_files_metadata = kb_processor.get_files_metadata()

        # 检查并构建选定章节的知识图谱
        if not kg_processor.load_graph_from_cache(current_files_metadata):
            kg_thread = threading.Thread(target=kg_processor.populate_graph,
                                         args=(kb_processor.documents, kg_ready_event, current_files_metadata))
            kg_thread.start()

        # 创建向量存储（可能使用缓存）
        kb_processor.create_vector_store()
        kb_processor.extract_keywords()

    except Exception as e:
        print(f"知识库准备失败：{e}")
        # 添加这行代码，让程序暂停，以便您查看错误信息
        input("请按任意键查看错误信息...")
    return

    end_time = time.time()
    print(f"知识库准备完成！耗时：{end_time - start_time:.2f}秒\n")

    # 5. 用户选择难度
    exam_answers = []
    while True:
        difficulty_choice = input("请选择出题难度（简单/中等/困难）：").strip().lower()
        if difficulty_choice in ["简单", "中等", "困难"]:
            difficulty = difficulty_choice
            break
        else:
            print("输入无效，请重新输入。")

    print(f"\n您已选择**{difficulty}**难度。")
    print(f"本次考试共{TOTAL_QUESTIONS}题，满分{TOTAL_SCORE}分。")

    # 6. 循环出题和评分
    total_score = 0
    for i in range(TOTAL_QUESTIONS):
        print(f"\n--- 第{i + 1}题 ---")
        question = question_generator.generate_question(difficulty=difficulty)
        print(f"**问题**：{question}\n")

        user_answer = get_multiline_input("请输入你的答案（输入空行结束）：")

        is_abnormal, abnormal_reason = check_abnormal_answer(user_answer, question)

        if is_abnormal:
            score = 0
            feedback = f"检测到非正常答题行为，本题按0分处理。**具体原因**：{abnormal_reason}"
        else:
            print("\n正在评分，请稍候...")
            score, feedback = scoring_module.score_answer(question, user_answer, TOTAL_SCORE // TOTAL_QUESTIONS)

        total_score += score
        exam_answers.append({
            "question": question,
            "answer": user_answer,
            "score": score,
            "feedback": feedback
        })

        print(f"\n**得分**：{score}/{TOTAL_SCORE // TOTAL_QUESTIONS}分")
        print(f"**反馈**：\n{feedback}")

    # 7. 考试结束，输出总分和详情
    print("\n\n===== 考试结束 =====")
    print(f"您的总得分：{total_score} / {TOTAL_SCORE}分")

    # 8. 详细答案回顾
    print("\n--- 详细回顾 ---")
    for i, item in enumerate(exam_answers):
        print(f"\n--- 第{i + 1}题 ---")
        print(f"问题: {item['question']}")
        print(f"你的答案: {item['answer']}")
        print(f"得分: {item['score']}/{TOTAL_SCORE // TOTAL_QUESTIONS}分")
        print(f"反馈: {item['feedback']}")

    print("\n===== 系统已退出 =====")